<template>
  <view style="background-color: #fff; height: 100vh;">
    <up-overlay :show="croshow">
      <view style="position: absolute; z-index: 999;">
        <view style="overflow: hidden;">
          <up-icon
            name="close"
            class="float-item-left"
            color=" #00bed2;"
            size="20"
            @click="croshow = false"
          ></up-icon>
          <span class="float-item-center">选择图片</span>
          <span class="float-item-rignt" @click="uploadImg()">确定</span>
        </view>
      </view>
      <up-image
        style="background-color: black;"
        :src="state.options.img"
        mode="aspectFit"
        height="100vh"
        width="100%"
      ></up-image>
    </up-overlay>
    <view style="background-color: #2b85e4; padding: 40rpx;">
      <view
        style="width: 140rpx; height: 140rpx; border: 1px solid #fff; border-radius: 50%; margin: 0 auto;"
      >
        <up-avatar :src="state.avatar" size="120rpx" style="margin: 10rpx;" @click="updateAvatar"></up-avatar>
      </view>
    </view>
    <view style="padding: 40rpx;">
      <up-form
        :model="state.model1"
        ref="formRef"
        :rules="state.rules"
        labelWidth="160rpx"
        labelAlign="left"
      >
        <up-form-item label="姓名" prop="userInfo.nickName" class="u-border-bottom">
          <up-input
            placeholder="请输入内容"
            border="none"
            v-model="state.model1.userInfo.nickName"
          ></up-input>
        </up-form-item>
        <up-form-item label="性别" prop="userInfo.sex" class="u-border-bottom">
          <up-radio-group v-model="state.model1.userInfo.sex" size="36rpx">
            <up-radio shape="circle" label="男" name="1" labelSize="32rpx"></up-radio>
            <up-radio shape="circle" label="女" name="2" labelSize="32rpx" style="margin-left: 36rpx;"></up-radio>
          </up-radio-group>
        </up-form-item>
        <up-form-item label="手机号码" prop="userInfo.phonenumber" class="u-border-bottom">
          <up-input
            placeholder="请输入内容"
            type="number"
            border="none"
            v-model="state.model1.userInfo.phonenumber"
          ></up-input>
        </up-form-item>
        <up-form-item label="邮箱" prop="userInfo.email" class="u-border-bottom">
          <up-input
            placeholder="请输入内容"
            border="none"
            v-model="state.model1.userInfo.email"
          ></up-input>
        </up-form-item>
      </up-form>
    </view>
    <view style="padding: 40rpx;">
      <up-row gutter="32">
        <up-col span="12">
          <up-button
            icon="checkmark-circle"
            text="保存"
            type="primary"
            @click="save"
          ></up-button>
        </up-col>
      </up-row>
    </view>
	<!-- <up-action-sheet 
		:show="show"
		@close="show = false"
		description="头像上传"
		:actions="list" 
		@select="uploadAvatar" 
		cancelText="取消">
	</up-action-sheet> -->
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { updateUserProfile, uploadAvatar } from '@/api/user';
import { useStore } from 'vuex';
// @ts-ignore
import { toast } from '@/uni_modules/uview-plus';
// 引入 user.ts 中的类型
import type { UserInfo, UpdateProfileParams } from '@/types/user';
import { onLoad } from '@dcloudio/uni-app';

// 定义裁剪选项类型
interface CropOptions {
  img: string;
  autoCrop: boolean;
  info: boolean;
  autoCropWidth: number;
  autoCropHeight: number;
  outputType: string;
  filename: string;
}

// 定义表单校验规则类型
interface FormRules {
  [key: string]: {
    required?: boolean;
    message: string;
    trigger: string | string[];
    type?: string;
    pattern?: RegExp;
  }[];
}

// 定义状态类型
interface State {
  model1: {
    userInfo: UserInfo;
  };
  avatar: string;
  options: CropOptions;
  rules: FormRules;
}

const croshow = ref<boolean>(false);
const formRef = ref<any>(null);
const store = useStore();

const state = reactive<State>({
  model1: {
    userInfo: {
      avatar: '',
      nickName: '',
      sex: '0',
      phonenumber: '',
      email: '',
    }as UserInfo,
  },
  avatar: '',
  options: {
    img: 'https://img0.baidu.com/it/u=2191392668,814349101&fm=253&fmt=auto&app=138&f=JPEG',
    autoCrop: true,
    info: false,
    autoCropWidth: 200,
    autoCropHeight: 200,
    outputType: 'png',
    filename: 'avatar',
  },
  rules: {
    'userInfo.nickName': [
      { required: true, message: '用户昵称不能为空', trigger: 'blur' },
    ],
    'userInfo.email': [
      { required: true, message: '邮箱地址不能为空', trigger: 'blur' },
      {
        type: 'email',
        message: '请输入正确的邮箱地址',
        trigger: ['blur', 'change'],
      },
    ],
    'userInfo.phonenumber': [
      { required: true, message: '手机号码不能为空', trigger: 'blur' },
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur',
      },
    ],
  },
});

const getInfo = async () => {
  try {
    const res = await store.dispatch('Info');
    state.model1.userInfo.nickName = res.nickName;
    state.model1.userInfo.sex = res.sex;
    state.model1.userInfo.phonenumber = res.phonenumber;
    state.model1.userInfo.email = res.email;
    state.avatar = `${process.env.BASE_URL}${res.avatar}`;
  } catch (error) {
    console.error('获取用户信息失败', error);
  }
};

const save = async () => {
  try {
    await formRef.value.validate();
    // 这里可以根据 UpdateProfileParams 类型来传递参数
    const updateParams: UpdateProfileParams = {
      nickName: state.model1.userInfo.nickName,
      email: state.model1.userInfo.email,
	  sex : state.model1.userInfo.sex,
	  phonenumber : state.model1.userInfo.phonenumber
    };
    const response = await updateUserProfile(updateParams);
    toast('修改成功');
    // @ts-ignore
    store.commit('SET_USER', response.user);
  } catch (error) {
    console.error('表单验证失败', error);
  }
};

const updateAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    success: (res) => {
      state.options.img = res.tempFilePaths[0];
      croshow.value = true;
    },
  });
};

const uploadImg = async () => {
  croshow.value = false;
  try {
    const response = await uploadAvatar({
      // @ts-ignore
      filePath: state.options.img,
      name: 'avatarfile',
      formData: {
        avatarfile: 'avatar',
      },
    });
    // @ts-ignore
    state.avatar = `${process.env.BASE_URL}${response.imgUrl}`;
    toast("上传头像成功")
  } catch (error) {
    toast("上传头像失败" + error)
  }
};

onLoad(() => {
  getInfo();
});
</script>

<style lang="scss" scoped>
.float-item-left {
  float: left;
  padding: 20rpx;
  margin-left: 20rpx;
  color: #00bed2;
}
.float-item-center {
  float: left;
  padding: 10px;
  margin-left: 190rpx;
 color: #00bed2;
}
.float-item-rignt {
  float: right;
  padding: 10px;
  color: #00bed2;
  margin-left: 180rpx;
}
</style>
